<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rules\Password;

/**
 * 认证控制器
 */
class AuthController extends Controller
{
    //
    public function login(Request $request)
    {
        return view('auth.login', [
            'title' => '系统登录',
        ]);
    }

    public function doLogin(Request $request)
    {
        $credentials = $request->validate([
            'email' => ['required', 'email'],
            'password' => ['required'],
            'captcha' => 'required|captcha',
        ]);
        unset($credentials['captcha']);
        $remember = $request->remember;
        if (Auth::attempt($credentials, $remember)) {
            $request->session()->regenerate();

            return redirect()->route('admin.dashboard');
        }

        return back()->withErrors([
            'email' => '提供的凭据与我们的记录不匹配。',
        ])->onlyInput('email');
    }

    public function logout(Request $request)
    {
        Auth::logout();
        return redirect('/');
    }

    public function register(Request $request)
    {
        return view('auth.register', [
            'title' => '注册',
        ]);
    }

    public function doRegister(Request $request)
    {
        $credentials = $request->validate([
            'email' => ['required', 'email', 'unique:users'],
            'password' => ['required', 'confirmed', Password::min(8)->mixedCase()->numbers()->symbols()],
            'captcha' => 'required|captcha',
        ]);
        // 执行注册
        $user = new User();
        $user->email = $request->email;
        $user->password = bcrypt($request->password);
        $user->name = $request->email;
        $suc = $user->save();
        if ($suc) {
            Auth::login($user);
            $request->session()->regenerate();

            return redirect()->route('admin.dashboard');
        } else {
            return back()->withErrors([
                'email' => '注册失败',
            ])->onlyInput('email');
        }
    }
}
